﻿//-----------------------------------------------------------------------
// <copyright file="SetupService.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Application.Services{    using System;
    using System.Globalization;
    using System.Linq;
    using AbstractSaaSTemplate.Application.Configuration;
    using AbstractSaaSTemplate.Application.Localization;
    using AbstractSaaSTemplate.Application.Templates;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Domain.Models.ValueObjects;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Domain.Services;
    using AbstractSaaSTemplate.Domain.Services.Results;
    using OOHM.Framework.Configuration;
    using OOHM.Framework.Security.Cryptography;

    /// <summary>
    /// Implements 'ISetupService' and all its contract, providing
    /// intelligent services to 'Sales' concern of the business.
    /// </summary>
    public class SetupService : ISetupService
    {
        /// <summary>
        /// Initializes a new instance of the SetupService class.
        /// </summary>
        /// <param name="repositoryForMembership">The repository to operate 'Memberships'.</param>
        /// <param name="repositoryForTemplates">The repository to operate 'Templates'.</param>
        /// <param name="repositoryForMessaging">The repository to operate 'Messaging'.</param>
        public SetupService(
            IMembershipRepository repositoryForMembership,
            ITemplatesRepository repositoryForTemplates,
            IMessagingRepository repositoryForMessaging)
        {
            this.RepositoryForMembership = repositoryForMembership;
            this.RepositoryForTemplates = repositoryForTemplates;
            this.RepositoryForMessaging = repositoryForMessaging;
        }

        /// <summary>
        /// Gets the repository to operate 'Memberships'.
        /// </summary>
        public IMembershipRepository RepositoryForMembership { get; private set; }

        /// <summary>
        /// Gets the repository to opreate 'Templates'.
        /// </summary>
        public ITemplatesRepository RepositoryForTemplates { get; private set; }

        /// <summary>
        /// Gets the repository to opreate 'Messaging'.
        /// </summary>
        public IMessagingRepository RepositoryForMessaging { get; private set; }

        /// <summary>
        /// Runs the installation procedures for the software.
        /// </summary>
        /// <param name="encryptionParaphrase">The paraphrase used to generated the encryption key.</param>
        /// <param name="staffAdministratorEmail">The e-mail linked to the administrator of the staff, which will receive the administrator password.</param>
        /// <param name="connectionString">The connection string for the database.</param>
        /// <param name="blobsRootPath">The blobs root folder.</param>
        /// <param name="blobsBaseLocation">The base url for blobs.</param>
        /// <param name="smtpHost">The smtp host which will be setup to the system.</param>
        /// <param name="smtpPort">The port of the smtp server.</param>
        /// <param name="smtpLogin">The login for the smtp server.</param>
        /// <param name="smtpPassword">The password for the smtp server.</param>
        /// <param name="smtpRequiresSsl">The value indicating whether the smtp server requires SSL.</param>
        /// <param name="emailDefaultSenderName">The name for the system default e-mail sender.</param>
        /// <param name="emailDefaultSenderEmailAddress">The e-mail address for the system default e-mail sender.</param>
        /// <param name="baseAppDomain">The base domain in which the application will be used.</param>
        /// <returns>Returns the installation results.</returns>
        public SetupInstallationResult RunInstall(
            string encryptionParaphrase,
            string staffAdministratorEmail,
            string connectionString,
            string blobsRootPath,
            string blobsBaseLocation,
            string smtpHost,
            int smtpPort,
            string smtpLogin,
            string smtpPassword,
            bool smtpRequiresSsl,
            string emailDefaultSenderName,
            string emailDefaultSenderEmailAddress,
            string baseAppDomain)
        {
            if (string.IsNullOrWhiteSpace(staffAdministratorEmail))
            {
                throw new ArgumentNullException("staffAdministratorEmail");
            }

            if (string.IsNullOrWhiteSpace(smtpHost))
            {
                throw new ArgumentNullException("smtpHost");
            }

            if (string.IsNullOrWhiteSpace(emailDefaultSenderName))
            {
                throw new ArgumentNullException("emailDefaultSenderName");
            }

            if (string.IsNullOrWhiteSpace(emailDefaultSenderEmailAddress))
            {
                throw new ArgumentNullException("emailDefaultSenderEmailAddress");
            }

            if (string.IsNullOrWhiteSpace(blobsRootPath))
            {
                throw new ArgumentNullException("blobsRootPath");
            }

            if (Configurator.GetConfigurationByKey<bool>(ConfigurationKeys.Installed))
            {
                return new SetupInstallationResult(SetupInstallationResultState.TheApplicationHasAlreadyBeenInstalled);
            }
            
            // step 1 -> create the staff administrator
            var password = Guid.NewGuid().ToString().Substring(0, 6).ToUpperInvariant();
            var step1Results = this.PerformInstallationStep01(
                encryptionParaphrase,
                staffAdministratorEmail,
                password,
                connectionString,
                blobsRootPath,
                blobsBaseLocation);

            if (!step1Results)
            {
                return new SetupInstallationResult(SetupInstallationResultState.StaffAdministratorAlreadyExists);
            }

            // step 2 -> setup the e-mail infra-structure
            var step2Results = PerformInstallationStep02(
                smtpHost,
                smtpPort,
                smtpLogin,
                smtpPassword,
                smtpRequiresSsl,
                emailDefaultSenderName,
                emailDefaultSenderEmailAddress,
                baseAppDomain);

            if (!step2Results)
            {
                return new SetupInstallationResult(SetupInstallationResultState.EmailServiceCouldNotBeSetup);
            }

            // step 3 -> setup the e-mail templates
            var step3Results = this.PerformInstallationStep03();

            if (!step3Results)
            {
                return new SetupInstallationResult(SetupInstallationResultState.TemplatesCouldNotBeInstalled);
            }

            CommitInstallation();

            return new SetupInstallationResult(
                SetupInstallationResultState.Success,
                password);
        }

        /// <summary>
        /// Performs the step 2 of installation.
        /// </summary>
        /// <param name="smtpHost">The smtp host which will be setup to the system.</param>
        /// <param name="smtpPort">The port of the smtp server.</param>
        /// <param name="smtpLogin">The login for the smtp server.</param>
        /// <param name="smtpPassword">The password for the smtp server.</param>
        /// <param name="smtpRequiresSsl">The value indicating whether the smtp server requires SSL.</param>
        /// <param name="emailDefaultSenderName">The name for the system default e-mail sender.</param>
        /// <param name="emailDefaultSenderEmailAddress">The e-mail address for the system default e-mail sender.</param>
        /// <param name="baseAppDomain">The base domain in which the application will be used.</param>
        /// <returns>Returns the installation results for the step.</returns>
        private static bool PerformInstallationStep02(
            string smtpHost,
            int smtpPort,
            string smtpLogin,
            string smtpPassword,
            bool smtpRequiresSsl,
            string emailDefaultSenderName,
            string emailDefaultSenderEmailAddress,
            string baseAppDomain)
        {
            // we check if any smtp configuration already exists
            // if any exists, it means that the system has been
            // installed previously and cannot proceed
            var configsWhichWillBeCreated = new[]
            {
                new { Key = ConfigurationKeys.SystemSmtpHost, Value = smtpHost },
                new { Key = ConfigurationKeys.SystemSmtpPort, Value = smtpPort.ToString(CultureInfo.InvariantCulture) },
                new { Key = ConfigurationKeys.SystemSmtpLogin, Value = smtpLogin },
                new { Key = ConfigurationKeys.SystemSmtpPassword, Value = smtpPassword },
                new { Key = ConfigurationKeys.SystemSmtpRequiresSsl, Value = smtpRequiresSsl.ToString(CultureInfo.InvariantCulture) },
                new { Key = ConfigurationKeys.SystemDefaultEmailSenderName, Value = emailDefaultSenderName },
                new { Key = ConfigurationKeys.SystemDefaultEmailSenderAddress, Value = emailDefaultSenderEmailAddress },
                new { Key = ConfigurationKeys.AppBaseDomain, Value = baseAppDomain }
            };

            // now, if none of the configuration entries have been
            // found, we shall create this configuration entries
            // such as defined in the setup.
            foreach (var config in configsWhichWillBeCreated)
            {
                Configurator.AddOrUpdateConfigurationEntry(
                    config.Key,
                    config.Value);
            }

            // finally, we respond true to this installation step.
            return true;
        }

        /// <summary>
        /// Commits the installation in the config file.
        /// </summary>
        private static void CommitInstallation()
        {
            // we check if any smtp configuration already exists
            // if any exists, it means that the system has been
            // installed previously and cannot proceed
            var configsWhichWillBeCreated = new[]
            {
                new { Key = ConfigurationKeys.Installed, Value = true.ToString() }
            };

            // now, if none of the configuration entries have been
            // found, we shall create this configuration entries
            // such as defined in the setup.
            foreach (var config in configsWhichWillBeCreated)
            {
                Configurator.AddOrUpdateConfigurationEntry(
                    config.Key,
                    config.Value);
            }
        }

        /// <summary>
        /// Performs the step 1 of installation.
        /// </summary>
        /// <param name="encryptionParaphrase">The paraphrase used to generated the encryption key.</param>
        /// <param name="staffAdministratorEmail">The e-mail of the staff administrator.</param>
        /// <param name="password">The password for the staff administrator</param>
        /// <param name="connectionString">The connection string for the database.</param>
        /// <param name="blobsRootPath">The blobs root folder.</param>
        /// <param name="blobsBaseLocation">The base url for blobs.</param>
        /// <returns>Returns the installation results for the step.</returns>
        private bool PerformInstallationStep01(
            string encryptionParaphrase,
            string staffAdministratorEmail,
            string password,
            string connectionString,
            string blobsRootPath,
            string blobsBaseLocation)
        {
            // we check if any configuration already exists
            // if any exists, it means that the system has been
            // installed previously and cannot proceed
            var configsWhichWillBeCreated = new[]
            {
                new { Key = ConfigurationKeys.EncryptionParaphrase, Value = encryptionParaphrase },
                new { Key = ConfigurationKeys.ConnectionForSQL2K8, Value = connectionString },
                new { Key = ConfigurationKeys.BlobsRootDirectoryPath, Value = blobsRootPath },
                new { Key = ConfigurationKeys.BlobsBaseLocation, Value = blobsBaseLocation }
            };

            // now, if none of the configuration entries have been
            // found, we shall create this configuration entries
            // such as defined in the setup.
            foreach (var config in configsWhichWillBeCreated)
            {
                Configurator.AddOrUpdateConfigurationEntry(config.Key, config.Value);
            }

            // if the passphrase was not saved, we set it
            if (!Cypher.Initialized)
            {
                Cypher.InitializeService(encryptionParaphrase);
            }

            // we create the staff members            
            var staffAdmins = this.RepositoryForMembership.GetUsersByRole(
                AccessLevels.Distributor,
                AccessRoles.Administrator);

            if (staffAdmins == null && staffAdmins.FirstOrDefault() != null)
            {
                // if there are administrator users already, we cannot
                // re-install the application since it's be once installed
                return false;
            }

            // generates random password
            var entity = new User()
            {
                FirstName = Expressions.Administrator,
                LastName = Expressions.Distributor,

                AccessLevel = AccessLevels.Distributor,
                EmailAddress = staffAdministratorEmail,
                Credentials = new Credentials(staffAdministratorEmail, password)
            };

            // saves the new administrative member into the repository
            this.RepositoryForMembership.AddOrUpdateUser(entity);

            // plus generates an association between the member and the role.
            this.RepositoryForMembership.AssociateUserWithRole(
                entity.Id,
                AccessRoles.Administrator);

            // and we add the access to feature users management,
            // tenants management and to the security management
            var features = new[]
            {
                ControlledFeatures.Dashboard,
                ControlledFeatures.TenantsManagement,
                ControlledFeatures.UsersManagement,
                ControlledFeatures.RolesFeaturesManagement
            };
            
            foreach (var feature in features)
            {
                this.RepositoryForMembership.AssociateRoleWithFeature(
                    AccessLevels.Distributor,
                    AccessRoles.Administrator,
                    feature);
            }

            // finally, we respond true to this installation step.
            return true;
        }

        /// <summary>
        /// Installs the basic system templates.
        /// </summary>
        /// <returns>Returns true if successfull; otherwise returns false.</returns>
        private bool PerformInstallationStep03()
        {
            var templateForWelcomeMessage = new Template<EmailMessage>();
            templateForWelcomeMessage.Key = EmailTemplates.WelcomeMessageForAdministrator;
            templateForWelcomeMessage.CustomData.Subject = "Bem vindo ao {app-name}.";
            templateForWelcomeMessage.CustomData.Body = string.Concat(
                "Olá {receiver-name}!\n",
                "Bem vindo ao {app-name}.\n\n",
                "Confirmamos, através deste e-mail, que você é o ADMINISTRADOR deste serviço ",
                "em nome da empresa {client-company-display-name} ({client-company-name}).\n\n",
                "Para iniciar o uso do serviço, por favor acesse:\n",
                "{service-url}\n",
                "login: {client-administrator-login}\n",
                "senha: {client-administrator-password}\n\n",
                "É importante lembrar que o uso deste sistema pelos usuários de sua empresa ",
                "estarão, a partir de agora, sob sua responsabilidade.\n\n",
                "Ficamos muito satisfeitos de tê-los conosco.\n",
                "Um forte abraço,\n",
                "{sender-fullname}\n",
                "Administrador de Plataforma\n",
                "{app-name}");

            this.RepositoryForTemplates.AddOrUpdateTemplate(templateForWelcomeMessage);

            return true;
        }
    }
}


